import "./reset.css";
// import dayjs from "dayjs";
import roleForm from "../form/role.vue";
// import editForm from "../form/index.vue";
// import { zxcvbn } from "@zxcvbn-ts/core";
// import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
// import userAvatar from "@/assets/user.jpg";
// import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
// import ReCropperPreview from "@/components/ReCropperPreview";
import type { FormItemProps, RoleFormItemProps } from "../utils/types";
import {
  // getKeyList,
  // isAllEmpty,
  // hideTextAtIndex,
  deviceDetection
} from "@pureadmin/utils";
import {
  // getRoleIds,
  // getDeptList,
  getUserList,
  getAllRoleList,
  // getUserDetailList,
  disableUserAccount,
  enableUserAccount,
  resetUserPassword,
  // getRoleList,
  getCurrentUserRole,
  editCurrentUserRole,
  syncUserToBI
} from "@/api/system";

import {
  type Ref,
  h,
  ref,
  // toRaw,
  // watch,
  computed,
  reactive,
  onMounted
} from "vue";

export function useUser(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    name: "",
    status: "",
    account: ""
  });

  const formRef = ref();
  // const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  // const avatarInfo = ref();
  // const switchLoadMap = ref({});
  // const { switchStyle } = usePublicHooks();
  // const higherDeptOptions = ref();
  const treeData = ref([]);
  // const treeLoading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true, // 数据刷新后保留选项
      selectable: row => {
        return !row.id; // 只有 id 不存在时才允许选中
      }
    },
    {
      label: "账号状态",
      prop: "status",
      width: 90,
      cellRenderer: ({ row }) => {
        let text = "-";
        let color = "#666"; // 默认灰色

        if (row.status === "0") {
          text = "正常";
          color = "green";
        } else if (row.status === "1") {
          text = "停用";
          color = "red";
        } else if (row.status === "-1") {
          text = "未授权";
          color = "red";
        } else if (row.status === "-2") {
          text = "异常";
          color = "red";
        }

        return h(
          "span",
          {
            style: {
              color,
              fontWeight: "bold"
            }
          },
          text
        );
      }
    },
    {
      label: "用户名",
      prop: "account",
      minWidth: 130
    },
    {
      label: "姓名",
      prop: "name",
      minWidth: 130
    },
    {
      label: "部门",
      prop: "department",
      minWidth: 130
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 130
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });
  // // 重置的新密码
  // const pwdForm = reactive({
  //   newPwd: ""
  // });
  // const pwdProgress = [
  //   { color: "#e74242", text: "非常弱" },
  //   { color: "#EFBD47", text: "弱" },
  //   { color: "#ffa500", text: "一般" },
  //   { color: "#1bbf1b", text: "强" },
  //   { color: "#008000", text: "非常强" }
  // ];
  // // 当前密码强度（0-4）
  // const curScore = ref();
  const roleOptions = ref([]);

  function handleDisable(row) {
    disableUserAccount(row.id).then(res => {
      if (res.code === 0) {
        message("操作成功", { type: "success" });
        onSearch();
      }
    });
  }

  function handleEnable(row) {
    enableUserAccount(row.id).then(res => {
      if (res.code === 0) {
        message("操作成功", { type: "success" });
        onSearch();
      }
    });
  }

  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    message(`您删除了用户编号为${row.id}的这条数据`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量同步 */
  async function onbatchSync() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const data = curSelected.map(val => {
      return {
        account: val.account,
        password: "",
        organizationId: 682441144406085,
        roleId: 682458420211781,
        remark: val.remark ?? "",
        name: val.name ?? "",
        telephone: val.telephone ?? "",
        email: val.email ?? "",
        avatar: val.avatar ?? "",
        avatarurl: val.avatarurl ?? ""
      };
    });

    await syncUserToBI(data);

    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message("同步成功", {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  /**
   gh:工号
   xm:姓名
   pageSize:框架里面定义了是Number类型，但是后端需要传String类型所以强制转为String类型
   pageIndex:框架里面定义了是Number类型，后端需要传String类型所以强制转为String类型
   **/
  async function onSearch() {
    loading.value = true;
    const { data, total } = await getUserList({
      action: "public/get_roster_mixed",
      gh: form.account,
      xm: form.name,
      zt: form.status,
      pageSize: String(pagination.pageSize),
      pageIndex: String(pagination.currentPage)
    });
    pagination.total = total;

    dataList.value = data;
    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  // function formatHigherDeptOptions(treeList) {
  //   // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
  //   if (!treeList || !treeList.length) return;
  //   const newTreeList = [];
  //   for (let i = 0; i < treeList.length; i++) {
  //     treeList[i].disabled = treeList[i].status === 0 ? true : false;
  //     formatHigherDeptOptions(treeList[i].children);
  //     newTreeList.push(treeList[i]);
  //   }
  //   return newTreeList;
  // }

  // function openDialog(title = "新增", row?: FormItemProps) {
  //   addDialog({
  //     title: `${title}用户`,
  //     props: {
  //       formInline: {
  //         title,
  //         // higherDeptOptions: formatHigherDeptOptions(higherDeptOptions.value),
  //         parentId: row?.dept.id ?? 0,
  //         nickname: row?.nickname ?? "",
  //         account: row?.account ?? "",
  //         password: row?.password ?? "",
  //         phone: row?.phone ?? "",
  //         email: row?.email ?? "",
  //         sex: row?.sex ?? "",
  //         status: row?.status ?? 1,
  //         remark: row?.remark ?? ""
  //       }
  //     },
  //     width: "46%",
  //     draggable: true,
  //     fullscreen: deviceDetection(),
  //     fullscreenIcon: true,
  //     closeOnClickModal: false,
  //     contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
  //     beforeSure: (done, { options }) => {
  //       const FormRef = formRef.value.getRef();
  //       const curData = options.props.formInline as FormItemProps;
  //       function chores() {
  //         message(`您${title}了用户名称为${curData.name}的这条数据`, {
  //           type: "success"
  //         });
  //         done(); // 关闭弹框
  //         onSearch(); // 刷新表格数据
  //       }
  //
  //       FormRef.validate(valid => {
  //         if (valid) {
  //           console.log("curData", curData);
  //           // 表单规则校验通过
  //           if (title === "新增") {
  //             // 实际开发先调用新增接口，再进行下面操作
  //             chores();
  //           } else {
  //             // 实际开发先调用修改接口，再进行下面操作
  //             chores();
  //           }
  //         }
  //       });
  //     }
  //   });
  // }

  // const cropRef = ref();

  /** 上传头像 */
  // function handleUpload(row) {
  //   addDialog({
  //     title: "裁剪、上传头像",
  //     width: "40%",
  //     closeOnClickModal: false,
  //     fullscreen: deviceDetection(),
  //     contentRenderer: () =>
  //       h(ReCropperPreview, {
  //         ref: cropRef,
  //         imgSrc: row.avatar || userAvatar,
  //         onCropper: info => (avatarInfo.value = info)
  //       }),
  //     beforeSure: done => {
  //       console.log("裁剪后的图片信息：", avatarInfo.value);
  //       // 根据实际业务使用avatarInfo.value和row里的某些字段去调用上传头像接口即可
  //       done(); // 关闭弹框
  //       onSearch(); // 刷新表格数据
  //     },
  //     closeCallBack: () => cropRef.value.hidePopover()
  //   });
  // }

  // watch(
  //   pwdForm,
  //   ({ newPwd }) =>
  //     (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  // );

  /** 重置密码 */
  function handleReset(row) {
    resetUserPassword(row.id).then(res => {
      if (res.code === 0) {
        onSearch(); // 刷新表格数据
        message(`已成功重置 ${row.name} 用户的密码为${res.data}`, {
          type: "success"
        });
      }
    });
  }

  /** 分配角色 */
  async function handleRole(row) {
    // 选中的角色列表
    const { data } = await getCurrentUserRole(row.id);
    let ids = data.roleId;

    addDialog({
      title: `分配 ${row.name} 用户的角色`,
      props: {
        formInline: {
          // accont: row?.account ?? "",
          // nickname: row?.nickname ?? "",
          roleOptions: roleOptions.value ?? [],
          ids
        }
      },
      width: "400px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(roleForm),
      beforeSure: async (done, { options }) => {
        const curData = options.props.formInline as RoleFormItemProps;
        const _data = {
          roleId: curData.ids,
          password: row.password,
          remark: row.remark,
          name: row.name,
          telephone: row.telephone,
          email: row.email,
          avatar: row.avatar,
          organizationId: row.organizationId,
          avatarurl: row.avatarurl
        };
        const { code } = await editCurrentUserRole(row.id, _data);
        if (code === 0) {
          message(`已成功修改 ${row.name} 用户的角色`, {
            type: "success"
          });
          done(); // 关闭弹框
        }
      }
    });
  }

  onMounted(async () => {
    // treeLoading.value = true;
    onSearch();
    // // 角色列表
    roleOptions.value = (await getAllRoleList()).data.items;
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    // treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchSync,
    // openDialog,
    handleUpdate,
    handleDelete,
    // handleUpload,
    handleReset,
    handleRole,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    handleDisable,
    handleEnable
  };
}
